package com.wedo.mall.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.e.library.activity.EActivity;
import com.e.library.http.EApi;
import com.e.library.http.EClient;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.utils.ESPUtils;
import com.e.library.utils.EUtils;
import com.e.library.widget.EBadgeView;
import com.wedo.mall.R;
import com.wedo.mall.activity.goods.GoodsDetailActivity;
import com.wedo.mall.activity.login.WLogin;
import com.wedo.mall.dialog.WelcomeDialog;
import com.wedo.mall.entity.Shopping;
import com.wedo.mall.fragment.MainFragment;
import com.wedo.mall.fragment.AgentFragment;
import com.wedo.mall.fragment.ShoppingFragment;
import com.wedo.mall.fragment.UserFragment;
import com.wedo.mall.util.WUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;


public class MainActivity extends EActivity {

    public static final String EXTRA_TAB = "tab";
    public static final int TAB_MAIN = 0;
    public static final int TAB_AGENT = 1;
    public static final int TAB_SHOPPING = 2;
    public static final int TAB_USET = 3;


    public static void toShopping(EActivity activity){
        toMainActivity(activity,TAB_SHOPPING);
    }

    public static void toMain(EActivity activity){
        toMainActivity(activity,TAB_MAIN);
    }

    public static void toMainActivity(EActivity activity,int tab){
        Intent intent = new Intent(activity,MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(EXTRA_TAB,tab);
        activity.startActivity(intent);
        activity.defaultFinish();
    }

    @BindViews({R.id.tv_tab1, R.id.tv_tab2, R.id.tv_tab3, R.id.tv_tab4})
    List<TextView> tvs;
    @BindViews({R.id.iv_tab1, R.id.iv_tab2, R.id.iv_tab3, R.id.iv_tab4})
    List<ImageView> icons;

    public EBadgeView eBadgeView;
    @BindView(R.id.iv_tab3) ImageView iv_shopping;

    private List<Fragment> fragments = new ArrayList<>(4);

    @Override
    protected int layout() {
        return R.layout.activity_main;
    }

    @Override
    protected void onActivityCreated(Bundle state) {

        int tab = getIntent().getIntExtra(EXTRA_TAB,TAB_MAIN);

        toGuide();
        disableSwipeBack();
        statusBar(R.color.e_purple);
        fragments.add(MainFragment.with());
        fragments.add(AgentFragment.with());
        fragments.add(ShoppingFragment.with());
        fragments.add(UserFragment.with());

        onTabChanged(tab);

        eBadgeView = new EBadgeView(this);
        eBadgeView.setTargetView(iv_shopping);
        eBadgeView.setBadgeMargin(10,0,0,0);

        isLocationProviderEnabled();
        welcome();

        Uri uri = getIntent().getData();
        if(uri !=null) {
            String goods_id = uri.getQueryParameter("goods_id");
            GoodsDetailActivity.toDetail(this,goods_id);
        }
    }

    private void toGuide(){
        if(ESPUtils.getBoolean(this,"to_guide",true)){
            toActivity(GuideActivity.class);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        int tab = getIntent().getIntExtra(EXTRA_TAB,TAB_MAIN);
        onTabChanged(tab);

        if (tab !=TAB_SHOPPING){
            return;
        }
        if (!WLogin.logged(this)){
            return;
        }
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fl_fragment);
        if (fragment != null && fragment instanceof ShoppingFragment){
            /**刷新购物车*/
            ((ShoppingFragment) fragment).shopping();
        }
    }

    @OnClick({R.id.ll_tab1, R.id.ll_tab3, R.id.ll_tab2, R.id.ll_tab4})
    protected void onTabClick(View view) {
        switch (view.getId()) {
            case R.id.ll_tab1:
                onTabChanged(0);
                break;
            case R.id.ll_tab2:
                onTabChanged(1);
                break;
            case R.id.ll_tab3:
                onTabChanged(2);
                break;
            case R.id.ll_tab4:
                onTabChanged(3);
                break;
        }

    }

    public void onTabChanged(int position) {
        if(position <0 || position >3) {
            position =0;
        }

        final FragmentManager fm = getSupportFragmentManager();
        final FragmentTransaction tr = fm.beginTransaction();

        int count = tvs.size();
        for (int i = 0; i < count; i++) {
            icons.get(i).setSelected(false);
            tvs.get(i).setSelected(false);
            Fragment fragment = fragments.get(i);
            if (!fragment.isHidden()) {
                tr.hide(fragment);
            }
        }

        icons.get(position).setSelected(true);
        tvs.get(position).setSelected(true);

        Fragment fragment = fragments.get(position);
        if (fragment.isAdded()) {
            tr.show(fragment).commitAllowingStateLoss();
        } else {
            tr.add(R.id.fl_fragment, fragment).show(fragment).commitAllowingStateLoss();
        }

    }

    private long mExitTime = System.currentTimeMillis();

    private void onDoublePressExitApp() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            toast("再按一次退出程序");
            mExitTime = System.currentTimeMillis();

        } else {
            defaultFinish();
        }
    }

    @Override
    public void onBackPressed() {
        onDoublePressExitApp();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(WLogin.logged(getApplicationContext())) {
            shopping();
        }else {
            eBadgeView.setBadgeCount(0);
        }
    }

    /**获取购物车*/
    private void shopping(){
        EClient.with().post(EApi.SHOPPING_CAR, new EObserver() {
            @Override
            public void successful(EResponse response) {
                List<Shopping> list = response.list(Shopping.class);
                if (EUtils.isEmpty(list)){
                    eBadgeView.setBadgeCount(0);
                }else {
                    number(list);
                }
            }

            @Override
            public void failure(String msg) {
                eBadgeView.setBadgeCount(0);
            }
        });
    }

    public void updateNumber(int number){
        int count = eBadgeView.getBadgeCount()+number;
        eBadgeView.setBadgeCount(count);
    }

    /**计算购物车商品数量*/
    public int number(List<Shopping> list){
        int number = WUtils.goodsNumber(list);
        eBadgeView.setBadgeCount(number);
        return number;
    }

    public void number(int number){
        eBadgeView.setBadgeCount(number);
    }

    private void welcome(){
        boolean welcome = ESPUtils.getBoolean(this,"welcome",true);
        ESPUtils.setboolean(this,"welcome",false);
        if (welcome && !WLogin.logged(this)){
            WelcomeDialog.with(this).show();
        }

    }

    private void isLocationProviderEnabled(){
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        // 判断GPS模块是否开启，如果没有则开启
        if (locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            return;
        }

        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage(R.string.user_opengps);
        dialog.setPositiveButton(getResources().getString(R.string.ensure),
                new android.content.DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent, 0); // 设置完成后返回到原来的界面
                    }
                });
        dialog.setNeutralButton(getResources().getString(R.string.cancel), new android.content.DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                arg0.dismiss();
            }
        } );
        dialog.show();
    }

    /**Facebook sha*/
    private void sha(){
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.wedo.mall",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                String KeyHash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
                Log.i("KeyHash:", KeyHash);//两次获取的不一样  此处取第一个的值
                Toast.makeText(this, "FaceBook HashKey:"+KeyHash, Toast.LENGTH_SHORT).show();
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

}
